import { LockOutlined, UploadOutlined, UserOutlined } from '@ant-design/icons';
import { useMutation } from '@tanstack/react-query';
import { Button, Form, Input, message, Modal, Radio, Select, Upload } from 'antd';
import type { RcFile, UploadProps } from 'antd/es/upload';
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';

import api from '@/apis/api';
import { Messages } from '@/components/Messages/Messages';
import { Logger } from '@/components/useLogger';
import localINFO from '@/utils/localInfo';
import { getHeaders } from '@/utils/ReqInstance/axios';
import { UsbRegisterRole } from '@/utils/usbKey/register';

type DeviceInitModalProps = {
  visible: boolean;
  setVisible: (visible: boolean) => void;
};
const { Option } = Select;

const DeviceInitModal: React.FC<DeviceInitModalProps> = ({ visible, setVisible }) => {
  const navigate = useNavigate();
  const [keyImportMode, setKeyImportMode] = useState(0);
  const [form] = Form.useForm();
  const [file, setFile] = useState<RcFile | null>(null);
  const [fileList, setFileList] = useState<RcFile[]>([]);
  const getFileExtension = (filename: string) => {
    if (!filename) return ''; // 文件名为空的情况
    const parts = filename.split('.');
    if (!parts || parts.length === 0 || (parts[0] === '' && parts.length === 1)) {
      return ''; // 没有扩展名或隐藏文件
    }
    return parts.pop()?.toLowerCase() || ''; // 获取扩展名并转换为小写
  };

  const props: UploadProps = {
    name: 'file',
    maxCount: 1,
    accept: '.hust',
    headers: {
      ...getHeaders(),
      'accept-encoding': 'zh-CN,zh;q=0.9',
      'accept-language': 'gzip, deflate, brz',
    },
    beforeUpload: (file: RcFile) => {
      const allowedExtensions = ['hust'];
      const fileExtension = getFileExtension(file.name);
      const isAllowedExtension = allowedExtensions.includes(fileExtension);

      if (!isAllowedExtension) {
        Messages.error('请上传hust文件');
        return false;
      }
      const size = file.size;
      if (size === 0) {
        Messages.error('文件大小不能为0');
        return false;
      }

      if (size > 10 * 1024 * 1024) {
        Messages.error('上传文件限制在10MB以内');
        return false;
      }
      setFile(file); // Save the file to the state
      setFileList([file]); // Update the file list
      return false; // Prevent auto upload
    },
    onRemove: () => {
      setFile(null);
      setFileList([]);
    },
  };
  const InitDevice = useMutation({
    mutationFn: async (params: any) => {
      return api.InitDevice(params); // Use FormData for the request
    },
    onSuccess: (res: any) => {
      if (res?.success) {
        message.open({
          type: 'success',
          key: 'register',
          content: '初始化成功，跳转至登录页',
        });
        navigate('/login');
      } else {
        message.open({
          type: 'error',
          key: 'register',
          content: `初始化失败，${res?.message}`,
        });
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.open({
        type: 'error',
        key: 'register',
        content: '初始化失败',
      });
    },
  });

  const handleOk = async () => {
    try {
      await form.validateFields();
      message.open({
        type: 'info',
        key: 'register',
        content: '初始化中...请稍侯',
      });
      const publickey = await UsbRegisterRole();
      const values = form.getFieldsValue();
      InitDevice.mutate({
        file: file,
        grant: 0,
        username: values.name,
        password: values.password,
        public_key: publickey,
        log_class: values.log_level,
        generation: keyImportMode,
        key_password: values.keyPassword,
      });
    } catch (error: any) {
      Logger(error.message);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    setVisible(false);
  };

  const handleModeChange = (e: any) => {
    setKeyImportMode(e.target.value);
    setFile(null);
    setFileList([]);
  };

  return (
    <>
      <Modal
        title="设备初始化"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        cancelText="取消"
        okText="确定"
        okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <p style={{ marginLeft: 24, color: 'red' }}>
          提示：请插入usbkey，该操作会清空当前Usbkey内的角色信息！
        </p>
        <Form form={form} layout="horizontal" preserve={false} autoComplete="off">
          <Form.Item
            name="mode"
            label="密钥生成"
            rules={[{ required: true, message: '请选择密钥生成方式!' }]}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 18 }}
            initialValue={0}
          >
            <Radio.Group
              onChange={handleModeChange}
              value={keyImportMode}
              key={keyImportMode}
            >
              <Radio value={0}>自动生成</Radio>
              <Radio value={1}>导入</Radio>
            </Radio.Group>

            <Upload {...props} fileList={fileList}>
              <Button
                style={{ display: keyImportMode === 0 ? 'none' : '' }}
                icon={<UploadOutlined />}
              >
                导入
              </Button>
            </Upload>
          </Form.Item>
          <Form.Item
            name="keyPassword"
            label="密钥口令"
            rules={[{ required: keyImportMode !== 0, message: '请输入密钥口令!' }]}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 18 }}
            style={{ display: keyImportMode === 0 ? 'none' : '' }}
          >
            <Input.Password type="password" placeholder="请输入密钥口令" />
          </Form.Item>
          <Form.Item
            name="log_level"
            label="日志等级"
            rules={[{ required: true, message: '请选择日志等级!' }]}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 18 }}
          >
            <Select placeholder="请选择日志等级" allowClear>
              <Option value={1}>完全记录</Option>
              <Option value={2}>错误记录</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="name"
            label="管理员账号"
            rules={[{ required: true, message: '请输入管理员账号!' }]}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 18 }}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="请输入管理员账号"
              maxLength={30}
            />
          </Form.Item>
          <Form.Item
            name="password"
            label="管理员密码"
            rules={[{ required: true, message: '请输入管理员密码!' }]}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 18 }}
          >
            <Input.Password
              prefix={<LockOutlined />}
              type="password"
              placeholder="请输入管理员密码"
              minLength={4}
            />
          </Form.Item>
          <Form.Item
            label="确认密码"
            name="rpassword"
            rules={[
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject('两次密码不同！');
                },
              }),
              { required: true, message: '请再输入管理员密码!' },
            ]}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 18 }}
          >
            <Input.Password
              prefix={<LockOutlined />}
              autoComplete="new-password"
              placeholder="请再输入管理员密码"
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default React.memo(DeviceInitModal);
